/**
 * 通用UI组件库
 * 包含应用中复用的UI组件，提高代码复用性和维护性
 * 包括按钮、卡片、状态指示器、加载组件等
 */
import React from 'react';
import {
  View,
  Text,
  StyleSheet,
  TouchableOpacity,
  ActivityIndicator,
  Dimensions
} from 'react-native';
import { Ionicons } from '@expo/vector-icons';
import * as Progress from 'react-native-progress';

const { width } = Dimensions.get('window');

/**
 * 通用按钮组件
 * 支持多种样式和状态的按钮组件
 * @param {string} title - 按钮文字
 * @param {Function} onPress - 点击回调函数
 * @param {string} variant - 按钮样式变体 ('primary' | 'secondary' | 'success' | 'danger')
 * @param {boolean} disabled - 是否禁用
 * @param {string} icon - 图标名称
 * @param {boolean} loading - 是否显示加载状态
 * @param {Object} style - 自定义样式
 */
export function AppButton({ 
  title, 
  onPress, 
  variant = 'primary', 
  disabled = false, 
  icon, 
  loading = false,
  style 
}) {
  const getButtonStyle = () => {
    const baseStyle = [styles.button];
    
    switch (variant) {
      case 'primary':
        baseStyle.push(styles.primaryButton);
        break;
      case 'secondary':
        baseStyle.push(styles.secondaryButton);
        break;
      case 'success':
        baseStyle.push(styles.successButton);
        break;
      case 'danger':
        baseStyle.push(styles.dangerButton);
        break;
      default:
        baseStyle.push(styles.primaryButton);
    }
    
    if (disabled) {
      baseStyle.push(styles.disabledButton);
    }
    
    return baseStyle;
  };

  const getTextStyle = () => {
    const baseStyle = [styles.buttonText];
    
    switch (variant) {
      case 'secondary':
        baseStyle.push(styles.secondaryButtonText);
        break;
      default:
        baseStyle.push(styles.primaryButtonText);
    }
    
    if (disabled) {
      baseStyle.push(styles.disabledButtonText);
    }
    
    return baseStyle;
  };

  return (
    <TouchableOpacity
      style={[...getButtonStyle(), style]}
      onPress={onPress}
      disabled={disabled || loading}
      activeOpacity={0.8}
    >
      {loading ? (
        <ActivityIndicator size="small" color="#fff" />
      ) : (
        <View style={styles.buttonContent}>
          {icon && (
            <Ionicons 
              name={icon} 
              size={18} 
              color={variant === 'secondary' ? '#58CC02' : '#fff'} 
              style={styles.buttonIcon}
            />
          )}
          <Text style={getTextStyle()}>{title}</Text>
        </View>
      )}
    </TouchableOpacity>
  );
}

/**
 * 通用卡片组件
 * 用于包装内容的卡片容器
 * @param {ReactNode} children - 子组件
 * @param {Object} style - 自定义样式
 * @param {boolean} shadow - 是否显示阴影
 * @param {string} padding - 内边距大小 ('small' | 'medium' | 'large')
 */
export function AppCard({ children, style, shadow = true, padding = 'medium' }) {
  const getPaddingStyle = () => {
    switch (padding) {
      case 'small':
        return styles.cardSmallPadding;
      case 'large':
        return styles.cardLargePadding;
      default:
        return styles.cardMediumPadding;
    }
  };

  return (
    <View style={[
      styles.card,
      shadow && styles.cardShadow,
      getPaddingStyle(),
      style
    ]}>
      {children}
    </View>
  );
}

/**
 * 状态指示器组件
 * 用于显示不同状态的视觉指示器
 * @param {string} status - 状态类型 ('completed' | 'available' | 'locked' | 'in_progress')
 * @param {number} size - 图标大小
 * @param {boolean} showText - 是否显示状态文字
 */
export function StatusIndicator({ status, size = 24, showText = false }) {
  const getStatusConfig = () => {
    switch (status) {
      case 'completed':
        return {
          icon: 'checkmark-circle',
          color: '#4CAF50',
          text: '已完成',
          backgroundColor: '#E8F5E8'
        };
      case 'available':
        return {
          icon: 'play-circle',
          color: '#58CC02',
          text: '可学习',
          backgroundColor: '#E8F5E8'
        };
      case 'locked':
        return {
          icon: 'lock-closed',
          color: '#999',
          text: '未解锁',
          backgroundColor: '#f8f8f8'
        };
      case 'in_progress':
        return {
          icon: 'time',
          color: '#FF9500',
          text: '学习中',
          backgroundColor: '#FFF3E0'
        };
      default:
        return {
          icon: 'help-circle',
          color: '#999',
          text: '未知',
          backgroundColor: '#f8f8f8'
        };
    }
  };

  const config = getStatusConfig();

  return (
    <View style={[
      styles.statusContainer,
      { backgroundColor: config.backgroundColor }
    ]}>
      <Ionicons name={config.icon} size={size} color={config.color} />
      {showText && (
        <Text style={[styles.statusText, { color: config.color }]}>
          {config.text}
        </Text>
      )}
    </View>
  );
}

/**
 * 进度圆环组件
 * 显示圆形进度指示器
 * @param {number} progress - 进度百分比 (0-1)
 * @param {number} size - 圆环大小
 * @param {string} color - 进度颜色
 * @param {boolean} showPercentage - 是否显示百分比文字
 */
export function CircularProgress({ progress, size = 80, color = '#58CC02', showPercentage = true }) {
  return (
    <View style={[styles.circularProgressContainer, { width: size, height: size }]}>
      <Progress.Circle
        progress={progress}
        size={size}
        color={color}
        unfilledColor="#E5E5E5"
        borderWidth={0}
        thickness={6}
        showsText={showPercentage}
        formatText={() => `${Math.round(progress * 100)}%`}
        textStyle={styles.circularProgressText}
      />
    </View>
  );
}

/**
 * 加载指示器组件
 * 显示加载状态的组件
 * @param {boolean} visible - 是否显示
 * @param {string} text - 加载文字
 * @param {string} size - 指示器大小 ('small' | 'large')
 */
export function LoadingIndicator({ visible, text = '加载中...', size = 'large' }) {
  if (!visible) return null;

  return (
    <View style={styles.loadingContainer}>
      <ActivityIndicator 
        size={size} 
        color="#58CC02" 
      />
      <Text style={styles.loadingText}>{text}</Text>
    </View>
  );
}

/**
 * 空状态组件
 * 当列表或内容为空时显示的占位组件
 * @param {string} icon - 图标名称
 * @param {string} title - 标题文字
 * @param {string} description - 描述文字
 * @param {Function} onAction - 操作按钮回调
 * @param {string} actionText - 操作按钮文字
 */
export function EmptyState({ 
  icon = 'document-outline', 
  title = '暂无内容', 
  description = '目前还没有相关数据',
  onAction,
  actionText = '刷新'
}) {
  return (
    <View style={styles.emptyStateContainer}>
      <Ionicons name={icon} size={64} color="#ccc" />
      <Text style={styles.emptyStateTitle}>{title}</Text>
      <Text style={styles.emptyStateDescription}>{description}</Text>
      {onAction && (
        <AppButton
          title={actionText}
          onPress={onAction}
          variant="secondary"
          style={styles.emptyStateButton}
        />
      )}
    </View>
  );
}

/**
 * 分割线组件
 * 用于分隔内容的线条组件
 * @param {string} type - 分割线类型 ('full' | 'inset')
 * @param {Object} style - 自定义样式
 */
export function Divider({ type = 'full', style }) {
  return (
    <View style={[
      styles.divider,
      type === 'inset' && styles.insetDivider,
      style
    ]} />
  );
}

/**
 * 标签组件
 * 显示标签信息的小组件
 * @param {string} text - 标签文字
 * @param {string} variant - 标签样式 ('primary' | 'secondary' | 'success' | 'warning' | 'danger')
 * @param {Object} style - 自定义样式
 */
export function Tag({ text, variant = 'primary', style }) {
  const getTagStyle = () => {
    switch (variant) {
      case 'secondary':
        return styles.secondaryTag;
      case 'success':
        return styles.successTag;
      case 'warning':
        return styles.warningTag;
      case 'danger':
        return styles.dangerTag;
      default:
        return styles.primaryTag;
    }
  };

  return (
    <View style={[styles.tag, getTagStyle(), style]}>
      <Text style={[styles.tagText, getTagStyle()]}>{text}</Text>
    </View>
  );
}

const styles = StyleSheet.create({
  // 按钮样式
  button: {
    paddingHorizontal: 24,
    paddingVertical: 12,
    borderRadius: 8,
    alignItems: 'center',
    justifyContent: 'center',
    flexDirection: 'row',
    minHeight: 44,
  },
  buttonContent: {
    flexDirection: 'row',
    alignItems: 'center',
  },
  buttonIcon: {
    marginRight: 8,
  },
  buttonText: {
    fontSize: 16,
    fontWeight: '600',
  },
  
  // 按钮变体样式
  primaryButton: {
    backgroundColor: '#58CC02',
  },
  primaryButtonText: {
    color: '#fff',
  },
  secondaryButton: {
    backgroundColor: 'transparent',
    borderWidth: 2,
    borderColor: '#58CC02',
  },
  secondaryButtonText: {
    color: '#58CC02',
  },
  successButton: {
    backgroundColor: '#4CAF50',
  },
  dangerButton: {
    backgroundColor: '#F44336',
  },
  disabledButton: {
    backgroundColor: '#ccc',
    borderColor: '#ccc',
  },
  disabledButtonText: {
    color: '#999',
  },

  // 卡片样式
  card: {
    backgroundColor: '#fff',
    borderRadius: 12,
    borderWidth: 1,
    borderColor: '#f0f0f0',
  },
  cardShadow: {
    elevation: 2,
    shadowColor: '#000',
    shadowOffset: { width: 0, height: 1 },
    shadowOpacity: 0.1,
    shadowRadius: 2,
  },
  cardSmallPadding: {
    padding: 12,
  },
  cardMediumPadding: {
    padding: 16,
  },
  cardLargePadding: {
    padding: 20,
  },

  // 状态指示器样式
  statusContainer: {
    flexDirection: 'row',
    alignItems: 'center',
    paddingHorizontal: 8,
    paddingVertical: 4,
    borderRadius: 12,
  },
  statusText: {
    fontSize: 12,
    fontWeight: '500',
    marginLeft: 4,
  },

  // 圆形进度条样式
  circularProgressContainer: {
    alignItems: 'center',
    justifyContent: 'center',
  },
  circularProgressText: {
    fontSize: 14,
    fontWeight: '600',
    color: '#333',
  },

  // 加载指示器样式
  loadingContainer: {
    flex: 1,
    alignItems: 'center',
    justifyContent: 'center',
    padding: 20,
  },
  loadingText: {
    marginTop: 12,
    fontSize: 16,
    color: '#666',
    textAlign: 'center',
  },

  // 空状态样式
  emptyStateContainer: {
    flex: 1,
    alignItems: 'center',
    justifyContent: 'center',
    padding: 40,
  },
  emptyStateTitle: {
    fontSize: 18,
    fontWeight: '600',
    color: '#333',
    marginTop: 16,
    marginBottom: 8,
    textAlign: 'center',
  },
  emptyStateDescription: {
    fontSize: 14,
    color: '#666',
    textAlign: 'center',
    lineHeight: 20,
    marginBottom: 24,
  },
  emptyStateButton: {
    minWidth: 120,
  },

  // 分割线样式
  divider: {
    height: 1,
    backgroundColor: '#e0e0e0',
    width: '100%',
  },
  insetDivider: {
    marginLeft: 16,
    width: width - 32,
  },

  // 标签样式
  tag: {
    paddingHorizontal: 8,
    paddingVertical: 4,
    borderRadius: 12,
    alignSelf: 'flex-start',
  },
  tagText: {
    fontSize: 12,
    fontWeight: '500',
  },
  primaryTag: {
    backgroundColor: '#E8F5E8',
    color: '#58CC02',
  },
  secondaryTag: {
    backgroundColor: '#E3F2FD',
    color: '#2196F3',
  },
  successTag: {
    backgroundColor: '#E8F5E8',
    color: '#4CAF50',
  },
  warningTag: {
    backgroundColor: '#FFF3E0',
    color: '#FF9500',
  },
  dangerTag: {
    backgroundColor: '#FFEBEE',
    color: '#F44336',
  },
});